<template style="overflow-y: scroll; overflow-x: hidden; height: 100%">
  <div>
    <el-drawer
      title="分配任务"
      size="61%"
      :visible.sync="visibility"
      custom-class="demo-drawer"
    >
      <div class="demo-drawer__content">
        <el-form
          v-if="currentOrder"
          ref="dataForm"
          :model="currentOrder"
          label-position="right"
          label-width="120px"
        >
          <el-row v-if="currentOrder">
            <el-col :span="8">
              <el-form-item label="通知单号">
                {{ currentOrder.manufactureOrderCode }}
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="类型">
                {{ formatByKeyValue(orderTypeOptions, currentOrder.orderType) }}
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="计划日期">
                {{ currentOrder.expectManufactureDate }}
              </el-form-item>
            </el-col>
          </el-row>
          <div v-if="currentOrder.orderType === ORDER_TYPE_SPLIT">
            <div
              v-for="(
                goodsGroup, goodsGroupIndex
              ) in currentOrder.goodsMap.entries()"
              :key="goodsGroup.key"
              style="margin-bottom: 6px"
            >
              <el-table
                :data="goodsGroup.value"
                highlight-current-row
                :show-header="goodsGroupIndex === 0"
              >
                <el-table-column width="30px">
                  <template slot-scope="{ $index }">
                    <span v-if="$index === 0">
                      {{ goodsGroupIndex + 1 }}
                    </span>
                  </template>
                </el-table-column>
                <el-table-column width="70px">
                  <template slot-scope="{ row }">
                    <span
                      :class="row.type === 1 ? 'success-color' : 'danger-color'"
                    >
                      {{ formatByKeyValue(splitGoodsTypeOptions, row.type) }}
                    </span>
                  </template>
                </el-table-column>
                <el-table-column
                  :key="Math.random()"
                  label="识别码"
                  prop="goodsFullCode"
                  width="150px"
                />
                <el-table-column
                  label="货号"
                  prop="goodsCode"
                  min-width="150px"
                />
                <el-table-column label="简称" prop="goodsAbbr" width="150px" />
                <el-table-column
                  label="批号"
                  prop="goodsBatchCode"
                  width="150px"
                />
                <!-- <el-table-column label="浓度" width="100px">
                <template slot-scope="{ row }">
                  {{ row.concentration }} {{ row.concentrationUnit }}
                </template>
              </el-table-column>
              <el-table-column
                label="失效日期"
                prop="expirationDate"
                width="100px"
              /> -->
                <el-table-column label="规格" width="100px">
                  <template slot-scope="{ row }">
                    {{ row.specification }} {{ row.unit }}
                  </template>
                </el-table-column>
                <!-- <el-table-column label="个数" prop="expectCount" width="50px" /> -->
                <el-table-column
                  label="数量"
                  prop="expectQuantity"
                  width="100px"
                >
                  <template slot-scope="{ row }">
                    <span> {{ row.expectQuantity }}{{ row.unit }} </span>
                  </template>
                </el-table-column>
                <el-table-column label="分装人" width="100px">
                  <template slot-scope="{ row, $index }">
                    <span v-if="$index === 0">{{
                      row.manufactureUserName
                    }}</span>
                  </template>
                </el-table-column>
                <el-table-column label="备注" min-width="200px">
                  <template slot-scope="{ row, $index }">
                    <el-input v-if="row.type === 2" v-model="row.memo" />
                  </template>
                </el-table-column>
                <el-table-column width="150" fixed="right">
                  <template slot-scope="{ row, $index }">
                    <el-button
                      v-if="row.type === 2"
                      type="text"
                      @click="handleAddMeForSplit(goodsGroup.value)"
                    >
                      分配给我
                    </el-button>
                    <el-button
                      v-if="row.type === 2"
                      type="text"
                      @click="handleOpenAddUserForSplit(goodsGroup.value)"
                    >
                      分配其他
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>
          <el-table
            v-if="
              currentOrder.orderType === ORDER_TYPE_MANUFACTURE &&
                currentOrder.goodsList &&
                currentOrder.goodsList.length > 0
            "
            :data="currentOrder.goodsList"
            highlight-current-row
          >
            <el-table-column width="30px">
              <template slot-scope="{ $index }">
                <span>
                  {{ $index + 1 }}
                </span>
              </template>
            </el-table-column>
            <el-table-column
              label="识别码"
              prop="goodsFullCode"
              width="150px"
            />
            <el-table-column label="货号" prop="goodsCode" min-width="150px" />
            <el-table-column label="简称" prop="goodsAbbr" width="150px" />
            <el-table-column label="批号" prop="goodsBatchCode" width="100px" />
            <el-table-column label="数量" prop="expectQuantity" width="100px">
              <template slot-scope="{ row }">
                <span> {{ row.expectQuantity }}{{ row.unit }} </span>
              </template>
            </el-table-column>
            <el-table-column
              label="生产人"
              prop="manufactureUserName"
              width="100px"
            />
            <el-table-column label="备注" min-width="200px">
              <template slot-scope="{ row }">
                <el-input v-model="row.memo" />
              </template>
            </el-table-column>
            <el-table-column width="150">
              <template slot-scope="{ row, $index }">
                <el-button
                  type="text"
                  @click="handleAddMeForManufacture(row, $index)"
                >
                  分配给我
                </el-button>
                <el-button
                  type="text"
                  @click="handleOpenAddUserForManufacture(row, $index)"
                >
                  分配其他
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-form-item>
            <el-button @click="handleClose">取消</el-button>
            <!-- <el-button @click="handleAverageAssign">平均分配</el-button> -->
            <el-button type="primary" :loading="loading" @click="handleCommit">
              确定
            </el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-drawer>
    <SearchUser
      :search-personnel-data="searchUserData"
      @dataListData="handleSearchUser"
    />
  </div>
</template>

<script>
import { formatByKeyValue } from '@/utils'
import { saveAllManufactureTask } from '@/api/mes/manufactureTask.js'
import { mapGetters } from 'vuex'

import SearchUser from '@/components/SearchUser/SearchPersonnel.vue'

export default {
  components: { SearchUser },
  props: {
    visible: {
      required: true,
      type: Boolean
    },
    orderTypeOptions: {
      type: Array,
      default: null
    },
    manufactureGoodsTypeOptions: {
      type: Array,
      default: null
    },
    splitGoodsTypeOptions: {
      type: Array,
      default: null
    },
    currentOrder: {
      type: Object,
      default: null
    }
  },
  data() {
    return {
      ORDER_TYPE_SPLIT: 1,
      ORDER_TYPE_MANUFACTURE: 2,
      BEFORE_SPLIT: 2,
      loading: false,
      currentGoodsList: [],
      currentGoods: null,
      currentGoodsIndex: -1,
      searchUserData: {}
    }
  },
  computed: {
    visibility: {
      get() {
        return this.visible
      },
      set(val) {
        this.$emit('update:visible', val)
      }
    },
    ...mapGetters(['userName', 'userId'])
  },
  watch: {
    visible(value) {
      if (value) {
        this.currentGoodsList = []
        this.currentGoods = null
        this.currentGoodsIndex = -1
        this.searchUserData = {}
      }
    }
  },
  methods: {
    formatByKeyValue,
    handleAddMeForSplit(list) {
      list.forEach((e, i) => {
        e.manufactureUserId = this.userId
        e.manufactureUserName = this.userName
        this.$set(list, i, e)
      })
    },
    handleOpenAddUserForSplit(list) {
      this.currentGoodsList = list
      this.currentGoods = null
      this.currentGoodsIndex = -1
      this.searchUserData = {
        dialogVisible: true,
        appendToBody: true
      }
    },
    handleAddMeForManufacture(row, index) {
      row.manufactureUserId = this.userId
      row.manufactureUserName = this.userName
      this.$set(this.currentOrder.goodsList, index, row)
    },
    handleOpenAddUserForManufacture(row, index) {
      this.currentGoodsList = null
      this.currentGoods = row
      this.currentGoodsIndex = index
      this.searchUserData = {
        dialogVisible: true,
        appendToBody: true
      }
    },
    handleSearchUser(value) {
      if (value && value instanceof Array && value.length > 0) {
        const user = value[0]
        if (this.currentGoodsList) {
          this.currentGoodsList.forEach((e, i) => {
            e.manufactureUserId = user.id
            e.manufactureUserName = user.label
            this.$set(this.currentGoodsList, i, e)
          })
        } else {
          this.currentGoods.manufactureUserId = user.id
          this.currentGoods.manufactureUserName = user.label
          this.$set(
            this.currentOrder.goodsList,
            this.currentGoodsIndex,
            this.currentGoods
          )
        }
      }
    },
    handleClose() {
      this.visibility = false
    },
    handleCommit() {
      console.log(this.currentOrder)
      let msg = null
      this.currentOrder.goodsList.forEach((e) => {
        if (!e.manufactureUserId) {
          msg = '未给货品【' + e.goodsCode + '】分配人员'
          return
        }
      })
      if (msg) {
        this.$message.warning(msg)
        return
      }
      const manufactureTaskArray = []
      if (this.currentOrder.orderType === this.ORDER_TYPE_SPLIT) {
        let manufactureUserId = null
        let manufactureTask = null
        this.currentOrder.goodsList.forEach((e) => {
          if (manufactureUserId !== e.manufactureUserId) {
            manufactureUserId = e.manufactureUserId
            manufactureTask = {
              manufactureOrderId: this.currentOrder.manufactureOrderId,
              manufactureUserId: manufactureUserId,
              manufactureUserName: e.manufactureUserName,
              memo: e.memo,
              goodsList: [
                {
                  manufactureOrderGoodsId: e.manufactureOrderGoodsId
                }
              ]
            }
            manufactureTaskArray.push(manufactureTask)
          } else {
            manufactureTask.goodsList.push({
              manufactureOrderGoodsId: e.manufactureOrderGoodsId
            })
          }
        })
      } else if (this.currentOrder.orderType === this.ORDER_TYPE_MANUFACTURE) {
        this.currentOrder.goodsList.forEach((e) => {
          manufactureTaskArray.push({
            manufactureOrderId: this.currentOrder.manufactureOrderId,
            manufactureUserId: e.manufactureUserId,
            manufactureUserName: e.manufactureUserName,
            memo: e.memo,
            goodsList: [
              {
                manufactureOrderGoodsId: e.manufactureOrderGoodsId
              }
            ]
          })
        })
      }
      saveAllManufactureTask(manufactureTaskArray).then((response) => {
        this.visibility = false
        this.$emit('pagination')
      })
    }
    // handleAverageAssign() {
    //   if (this.list && this.list.length) {
    //     const averageCount = parseFloat(
    //       (this.currentOrder.expectCount / this.list.length).toFixed(3)
    //     )
    //     let sum = 0
    //     for (let i = 0, len = this.list.length - 1; i < len; i++) {
    //       sum += averageCount
    //       this.list[i].expectCount = averageCount
    //     }
    //     console.log(sum)
    //     this.list[this.list.length - 1].expectCount = parseFloat(
    //       (this.currentOrder.expectCount - sum).toFixed(3)
    //     )
    //   }
    // },
    // handleCommit() {
    //   if (!this.list || this.list.length < 1) {
    //     this.$message.warning('请选择生产人员')
    //     return
    //   }
    //   let sum = 0
    //   for (let i = 0, len = this.list.length; i < len; i++) {
    //     if (this.list[i].expectCount <= 0) {
    //       this.$message.warning(
    //         '请输入生产人员' + this.list[i].manufactureUserName + '的生产数量'
    //       )
    //       return
    //     }
    //     sum += this.list[i].expectCount
    //   }
    //   if (this.currentOrder.expectCount !== sum) {
    //     this.$message.warning('计划生产数量未完全分配')
    //     return
    //   }
    //   saveAllManufactureTask(this.list).then((response) => {
    //     this.visibility = false
    //   })
    // }
  }
}
</script>

<style lang="scss">
</style>
